package com.atguigu.lease.common.aliyun;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(AliyunConfig.class)
public class AliyunProperties {

    @Autowired
    private AliyunConfig aliyunConfig;

    @Bean
    public  Client client(){
        Config config = new Config();
        config.setAccessKeyId(aliyunConfig.getAccessKeyId());
        config.setAccessKeySecret(aliyunConfig.getAccessKeySecret());
        config.setEndpoint(aliyunConfig.getEndpoint());
        try {
            return new Client(config);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static String sentSms(String phoneNumber, Client client) throws Exception {

        //生成验证码
        SpecCaptcha captcha = new SpecCaptcha(130, 48, 6);
        captcha.setCharType(2);
        String code = captcha.text();

        //发送短信
        //2.准备发送短信的对象
        SendSmsRequest smsRequest = new SendSmsRequest();
        smsRequest.setPhoneNumbers(phoneNumber);
        smsRequest.setSignName("阿里云短信测试");
        smsRequest.setTemplateCode("SMS_154950909");
        smsRequest.setTemplateParam("{\"code\":\""+code+"\"}");

        //3.发送短信
        SendSmsResponse sendSmsResponse = client.sendSms(smsRequest);
            if(sendSmsResponse.getStatusCode() == 200){
                System.out.println("短信测试成功!!!");
            }

        return code;
    }
}
